package com.totcy.baselibrary.utils;

import android.content.Context;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 类转换初始化
 */
public class TUtil {

    /**
     * 获取T的实例 调用public构造方法参数context
     * @param context
     * @param o
     * @param i
     * @param <T>
     * @return
     */
    public static <T> T getPresenterT(Context context, Object o, int i) {
        Type type = o.getClass().getGenericSuperclass();
        if (type != null) {
            if (type instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                Class<T> params = (Class<T>) parameterizedType.getActualTypeArguments()[i];
                if (params != null) {
                    try {
                        //获取指定的私有构造方法
                        Constructor<T> constructor = params.getDeclaredConstructor(Context.class);
                        //flag的值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。
                        constructor.setAccessible(true);
                        return constructor.newInstance(context);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    public static Class<?> forName(String className) {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
